package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "FireEquipmentServlet", value = "/FireEquipmentServlet")
public class FireEquipmentServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://172.18.64.254:3306/三人行?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String DB_USER = "webdb";
    private static final String DB_PASSWORD = "webdb";
    // 关键：修改为巡检系统实际部署路径（示例：若巡检系统与本系统部署在同一Tomcat，项目名为"firecontrol"）
    private static final String INSPECTION_SYSTEM_URL = "http://localhost:8080/firecontrol/InspectionSystemServlet";

    // 查询消防设备列表（逻辑不变）
    private List<Map<String, Object>> queryFireEquipments(String searchKey) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        String sql = "SELECT * FROM fire_equipment " +
                (searchKey != null && !searchKey.isEmpty() ? "WHERE equip_no LIKE ? OR location LIKE ? OR type LIKE ? " : "") +
                "ORDER BY create_time DESC";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            if (searchKey != null && !searchKey.isEmpty()) {
                String param = "%" + searchKey + "%";
                pstmt.setString(1, param);
                pstmt.setString(2, param);
                pstmt.setString(3, param);
            }
            ResultSet rs = pstmt.executeQuery();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", rs.getInt("id"));
                map.put("equipNo", rs.getString("equip_no"));
                map.put("type", rs.getString("type"));
                map.put("model", rs.getString("model"));
                map.put("location", rs.getString("location"));
                map.put("status", rs.getString("status"));
                map.put("lastCheck", rs.getString("last_check"));
                Timestamp createTime = rs.getTimestamp("create_time");
                map.put("createTime", createTime != null ? sdf.format(createTime) : "无记录");
                list.add(map);
            }
        }
        return list;
    }

    // 获取单个消防设备（逻辑不变）
    private Map<String, Object> getFireEquipment(int id) throws SQLException {
        Map<String, Object> map = new HashMap<>();
        String sql = "SELECT * FROM fire_equipment WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                map.put("id", rs.getInt("id"));
                map.put("equipNo", rs.getString("equip_no"));
                map.put("type", rs.getString("type"));
                map.put("model", rs.getString("model"));
                map.put("location", rs.getString("location"));
                map.put("status", rs.getString("status"));
                map.put("lastCheck", rs.getString("last_check"));
                Timestamp createTime = rs.getTimestamp("create_time");
                map.put("createTime", createTime != null ? sdf.format(createTime) : "无记录");
            }
        }
        return map;
    }

    // 保存消防设备（新增/更新）（逻辑不变）
    private void saveFireEquipment(Map<String, String> paramMap, boolean isUpdate) throws SQLException {
        String sql = isUpdate ?
                "UPDATE fire_equipment SET equip_no=?, type=?, model=?, location=?, status=?, last_check=? WHERE id=?" :
                "INSERT INTO fire_equipment (equip_no, type, model, location, status, last_check) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, paramMap.get("equipNo"));
            pstmt.setString(2, paramMap.get("type"));
            pstmt.setString(3, paramMap.get("model"));
            pstmt.setString(4, paramMap.get("location"));
            pstmt.setString(5, paramMap.get("status"));
            pstmt.setString(6, paramMap.get("lastCheck"));
            if (isUpdate) {
                pstmt.setInt(7, Integer.parseInt(paramMap.get("id")));
            }
            pstmt.executeUpdate();
        }
    }

    // 删除消防设备（逻辑不变）
    private void deleteFireEquipment(int id) throws SQLException {
        String sql = "DELETE FROM fire_equipment WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }
    }

    // 获取设备旧状态（逻辑不变）
    private String getOldStatus(int id) throws SQLException {
        String sql = "SELECT status FROM fire_equipment WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            return rs.next() ? rs.getString("status") : null;
        }
    }

    // 调用巡检系统接口创建巡检任务（核心优化）
    private void createInspectionTask(int equipmentId, String status) {
        // 1. 验证参数合法性
        if (equipmentId <= 0 || status == null || status.trim().isEmpty()) {
            System.err.println("无效的参数：equipmentId=" + equipmentId + ", status=" + status);
            return;
        }

        try {
            // 2. 构建完整请求URL（确保路径正确）
            URL url = new URL(INSPECTION_SYSTEM_URL);
            System.out.println("=== 开始调用巡检系统接口 ===");
            System.out.println("请求URL：" + url);

            // 3. 配置HTTP连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setConnectTimeout(10000); // 延长超时时间，避免网络延迟导致失败
            conn.setReadTimeout(10000);

            // 4. 构建请求参数（确保参数名与巡检系统一致）
            String params = "action=create" +
                    "&equipmentId=" + equipmentId +
                    "&equipmentStatus=" + URLEncoder.encode(status, "UTF-8"); // 强制编码中文
            System.out.println("请求参数：" + params);

            // 5. 发送请求
            try (OutputStream os = conn.getOutputStream()) {
                os.write(params.getBytes("UTF-8"));
                os.flush();
            }

            // 6. 读取响应（关键：获取完整响应内容用于调试）
            int responseCode = conn.getResponseCode();
            System.out.println("响应状态码：" + responseCode);

            // 读取响应体（区分正常响应和错误响应）
            InputStream is = (responseCode == 200) ? conn.getInputStream() : conn.getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder responseBody = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                responseBody.append(line);
            }
            br.close();
            System.out.println("响应内容：" + responseBody);
            System.out.println("=== 巡检系统接口调用结束 ===");

            // 7. 处理响应结果
            if (responseCode != HttpURLConnection.HTTP_OK) {
                System.err.println("创建巡检任务失败：状态码=" + responseCode + "，响应=" + responseBody);
            } else if (responseBody.toString().contains("\"success\":true")) {
                System.out.println("创建巡检任务成功：设备ID=" + equipmentId + "，状态=" + status);
            } else {
                System.err.println("巡检系统返回失败：" + responseBody);
            }

            conn.disconnect();
        } catch (Exception e) {
            System.err.println("调用巡检系统接口异常：" + e.getMessage());
            e.printStackTrace(); // 打印完整堆栈，快速定位错误（如URL错误、网络不通）
        }
    }
    // 在 FireEquipmentServlet 的 createInspectionTask 方法内，或单独写测试方法
    public void testInspectionApi() {
        try {
            URL url = new URL("http://localhost:8080/demo_war_exploded/InspectionSystemServlet");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            String params = "action=create&equipmentId=1&equipmentStatus=故障"; // 填真实设备 ID
            try (OutputStream os = conn.getOutputStream()) {
                os.write(params.getBytes("UTF-8"));
            }
            // 打印响应（验证是否能连通）
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("巡检系统响应：" + line);
            }
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 处理GET请求（逻辑不变）
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");
        try {
            if ("list".equals(action)) {
                String searchKey = request.getParameter("searchKey");
                out.println(toJsonArray(queryFireEquipments(searchKey)));
            } else if ("get".equals(action)) {
                String idStr = request.getParameter("id");
                if (idStr == null || idStr.isEmpty()) {
                    throw new IllegalArgumentException("缺少参数: id");
                }
                Map<String, Object> param = getFireEquipment(Integer.parseInt(idStr));
                out.println(param.isEmpty() ? "{\"error\": \"未找到对应记录\"}" : toJson(param));
            } else if ("delete".equals(action)) {
                String idStr = request.getParameter("id");
                if (idStr == null || idStr.isEmpty()) {
                    throw new IllegalArgumentException("缺少参数: id");
                }
                deleteFireEquipment(Integer.parseInt(idStr));
                out.println("{\"success\": true}");
            } else {
                out.println("{\"error\": \"无效的操作(action)\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }

    // 处理POST请求（优化状态变更判断逻辑）
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");
        try {
            if ("add".equals(action) || "update".equals(action)) {
                // 获取参数
                String equipNo = request.getParameter("equipNo");
                String type = request.getParameter("type");
                String location = request.getParameter("location");
                String status = request.getParameter("status");
                String idStr = request.getParameter("id");
                System.out.println("=== 处理设备更新 ===");
                System.out.println("设备ID：" + idStr + "，新状态：" + status);

                // 参数验证
                if (equipNo == null || equipNo.isEmpty() || type == null || type.isEmpty() ||
                        location == null || location.isEmpty() || status == null || status.isEmpty()) {
                    throw new IllegalArgumentException("参数不完整");
                }

                // 封装参数
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("equipNo", equipNo);
                paramMap.put("type", type);
                paramMap.put("model", request.getParameter("model") != null ? request.getParameter("model") : "");
                paramMap.put("location", location);
                paramMap.put("status", status);
                paramMap.put("lastCheck", request.getParameter("lastCheck") != null ? request.getParameter("lastCheck") : "");
                boolean isUpdate = "update".equals(action);
                if (isUpdate) {
                    if (idStr == null || idStr.isEmpty()) {
                        throw new IllegalArgumentException("缺少参数: id");
                    }
                    paramMap.put("id", idStr);
                }

                // 保存设备信息
                saveFireEquipment(paramMap, isUpdate);
                System.out.println("设备信息保存成功");

                // 状态变更判断（核心：只有更新操作且状态从正常→异常时触发）
                if (isUpdate) {
                    int equipmentId = Integer.parseInt(idStr);
                    String oldStatus = getOldStatus(equipmentId);
                    System.out.println("设备ID=" + equipmentId + "，旧状态：" + oldStatus + "，新状态：" + status);

                    // 定义异常状态列表（与巡检系统保持一致）
                    String[] abnormalStatuses = {"待检修", "故障", "已过期"};
                    boolean isNowAbnormal = false;
                    for (String s : abnormalStatuses) {
                        if (s.equals(status)) {
                            isNowAbnormal = true;
                            break;
                        }
                    }

                    // 触发条件：新状态是异常状态，且旧状态是正常（或空，如新增后立即更新为异常）
                    if (isNowAbnormal && ("正常".equals(oldStatus) || oldStatus == null)) {
                        System.out.println("满足状态变更条件，调用巡检系统创建任务...");
                        createInspectionTask(equipmentId, status); // 调用接口
                    } else {
                        System.out.println("不满足状态变更条件，不创建巡检任务");
                    }
                }

                out.println("{\"success\": true}");
            } else {
                out.println("{\"error\": \"无效的操作(action)\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }

    // JSON转换工具（逻辑不变）
    private String toJson(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean first = true;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) json.append(",");
            json.append("\"").append(entry.getKey()).append("\":");
            if (entry.getValue() instanceof String) {
                json.append("\"").append(entry.getValue()).append("\"");
            } else {
                json.append(entry.getValue());
            }
            first = false;
        }
        json.append("}");
        return json.toString();
    }

    private String toJsonArray(List<Map<String, Object>> list) {
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) json.append(",");
            json.append(toJson(list.get(i)));
        }
        json.append("]");
        return json.toString();
    }

    // 获取数据库连接（逻辑不变）
    private Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new SQLException("JDBC驱动加载失败", e);
        }
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }
}